﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TSV.Models;
using TSV.Library.Common;
using TSV.Library.Attributes;

namespace TSV.Areas.Administration.Controllers
{
    public class OrdersPartnerController : BaseController
    {
        private PartnerDao partnerDao = new PartnerDao();
        private CategoryDao catDao = new CategoryDao();
        private OrdersPartnerDao orderDao = new OrdersPartnerDao();
        // GET: /Administration/Orders/
        [CrmAuthorizeAttribute(Module = Modules.QL_Doi_Tac, Rights = Permissions.Doc)]
        public ActionResult Index()
        {
            ViewData[CommonDataKey.CATEGORY] = new SelectList(catDao.GetParentAndChildList(), "ID", "CategoryName");
            return View();
        }

        [CrmAuthorizeAttribute(Module = Modules.QL_Doi_Tac, Rights = Permissions.Doc)]
        /// <summary>
        /// Get and bind to grid
        /// </summary>
        /// <param name="optionSearch"></param>
        /// <returns></returns>
        public ActionResult GetListJQGrid(string name, string catId, string fromdate, string todate)
        {
            //grid constant => duy hung
            #region JQGrid Params

            string sortColumn = (Request.Params[GridConstants.SORT_COLUMN]).ToString();
            string sortOrder = (Request.Params[GridConstants.SORT_ORDER]).ToString();
            int pageIndex = Convert.ToInt32(Request.Params[GridConstants.PAGE_INDEX]);
            int rowCount = Convert.ToInt32(Request.Params[GridConstants.ROW_COUNT]);

            #endregion

            #region search
            string text = null;
            int categoryId = 0;
            string searchName = string.Empty;
            DateTime? dFromDate = null;
            DateTime? dToDate = null;
            if (!string.IsNullOrEmpty(name.Trim()) && !name.Trim().Equals(Constants.PARTNER_NAME))
            {
                text = name;
            }
            if (!string.IsNullOrEmpty(catId))
            {
                categoryId = int.Parse(catId);
            }
            if (!string.IsNullOrEmpty(fromdate))
            {
                try
                {
                    dFromDate = DateTime.Parse(fromdate);
                }
                catch
                { }

            }
            if (!string.IsNullOrEmpty(todate))
            {
                try
                {
                    dToDate = DateTime.Parse(todate);
                }
                catch
                { }
            }
            #endregion


            List<sp_GetOrderListResult> list = orderDao.GetList(text, categoryId, dFromDate, dToDate);

            int totalRecords = list.Count();
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)rowCount);
            int currentPage = CommonFunc.SetJqGridPageIndex(totalRecords, pageIndex, rowCount);
            var finalList = list.Skip((currentPage - 1) * rowCount)
                                   .Take(rowCount);

            var jsonData = new
            {
                total = totalPages,
                page = currentPage,
                records = totalRecords,
                rows = (
                    from m in finalList
                    select new
                    {
                        i = m.ID,
                        cell = new string[] {
                            m.ID.ToString(),
                            m.CodeID,
                            "<img alt=\"Hình\" width=\"100px\" height=\"100px\" src=\"/FileUpload/Images/Partner/" + m.Logo + "\"/>",
                            HttpUtility.HtmlEncode(m.PartnerName),
                            HttpUtility.HtmlEncode(m.Category),
                            m.Price.ToString(),
                            m.Quality.ToString(),
                            m.Discount.ToString(),
                            m.PriceDiscount.ToString(),
                            m.Total.ToString(),
                            m.Status == 1?"Thành Công":"Trả Lại",
                            m.Date.ToString(Constants.DATETIME_FORMAT),
                             "<input type=\"button\" class=\"icon edit\" title=\"Cập nhật\" onclick=\"JS_LIB.popup('/Administration/OrdersPartner/Edit/" + m.ID.ToString() + "', 'Cập nhật', 500)\" />"
                        }
                    }
                ).ToArray()
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        [CrmAuthorizeAttribute(Module = Modules.QL_Doi_Tac, Rights = Permissions.Them)]
        public ActionResult Create()
        {
            return View();
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        [CrmAuthorizeAttribute(Module = Modules.QL_Doi_Tac, Rights = Permissions.Them)]
        public ActionResult Create(OrdersPartner obj)
        {
            try
            {
                obj.PriceDiscount = obj.Price * obj.Discount / 100;
                obj.Total = (obj.Price * obj.Quality) - (obj.PriceDiscount * obj.Quality);
                obj.Date = DateTime.Now;
                Message msg = orderDao.Insert(obj);
                ShowMessage(msg);

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        [CrmAuthorizeAttribute(Module = Modules.QL_Doi_Tac, Rights = Permissions.Them)]
        public ActionResult Edit(string id)
        {
            OrdersPartner obj = orderDao.GetByID(int.Parse(id));
            ViewData["Status"] = new SelectList(orderDao.GetListStatus(), "Value", "Text", obj.Status);
            return View(obj);
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        [CrmAuthorizeAttribute(Module = Modules.QL_Doi_Tac, Rights = Permissions.Them)]
        public ActionResult Edit(OrdersPartner obj)
        {
            try
            {
                obj.PriceDiscount = obj.Price * obj.Discount / 100;
                obj.Total = (obj.Price * obj.Quality) - (obj.PriceDiscount * obj.Quality);
                Message msg = orderDao.Update(obj);
                ShowMessage(msg);

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        [CrmAuthorizeAttribute(Module = Modules.QL_Doi_Tac, Rights = Permissions.Xoa)]
        public ActionResult DeleteList(string id)
        {
            Message msg = partnerDao.DeleteList(id);
            ShowMessage(msg);
            return RedirectToAction("Index");
        }
    }
}
